package xymt.novaway.common.oss.factory;

import lombok.extern.slf4j.Slf4j;
import xymt.novaway.common.core.constant.CacheNames;
import xymt.novaway.common.core.utils.StringUtils;
import xymt.novaway.common.json.utils.JsonUtils;
import xymt.novaway.common.oss.constant.OssConstant;
import xymt.novaway.common.oss.core.LocalOssClient;
import xymt.novaway.common.oss.core.OssClient;
import xymt.novaway.common.oss.exception.OssException;
import xymt.novaway.common.oss.properties.OssProperties;
import xymt.novaway.common.redis.utils.CacheUtils;
import xymt.novaway.common.redis.utils.RedisUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 文件上传Factory
 *
 * @author NovaWay
 */
@Slf4j
public class OssFactory {

    private static final Map<String, Object> CLIENT_CACHE = new ConcurrentHashMap<>();
    private static final ReentrantLock LOCK = new ReentrantLock();

    /**
     * 获取默认实例
     */
    public static OssClient instance() {
        // 获取redis 默认类型
        String configKey = RedisUtils.getCacheObject(OssConstant.DEFAULT_CONFIG_KEY);
        if (StringUtils.isEmpty(configKey)) {
            throw new OssException("文件存储服务类型无法找到!");
        }
        return instance(configKey);
    }

    /**
     * 根据类型获取实例
     */
    public static OssClient instance(String configKey) {
        // 本地存储类型需要特殊处理，不能返回OssClient类型
        if ("local".equals(configKey)) {
            throw new OssException("本地存储类型请使用 OssFactory.instanceLocal() 方法获取客户端实例");
        }
        
        String json = CacheUtils.get(CacheNames.SYS_OSS_CONFIG, configKey);
        if (json == null) {
            throw new OssException("系统异常, '" + configKey + "'配置信息不存在!");
        }
        OssProperties properties = JsonUtils.parseObject(json, OssProperties.class);
        // 使用租户标识避免多个租户相同key实例覆盖
        String key = configKey;
        if (StringUtils.isNotBlank(properties.getTenantId())) {
            key = properties.getTenantId() + ":" + configKey;
        }
        
        Object cachedClient = CLIENT_CACHE.get(key);
        OssClient client = null;
        
        // 检查缓存的客户端是否为OssClient类型且配置相同
        if (cachedClient instanceof OssClient) {
            client = (OssClient) cachedClient;
            if (client.checkPropertiesSame(properties)) {
                return client;
            }
        }
        
        // 客户端不存在或配置不相同则重新构建
        LOCK.lock();
        try {
            // 双重检查
            cachedClient = CLIENT_CACHE.get(key);
            if (cachedClient instanceof OssClient) {
                client = (OssClient) cachedClient;
                if (client.checkPropertiesSame(properties)) {
                    return client;
                }
            }
            
            // 创建新的OssClient实例
            client = new OssClient(configKey, properties);
            CLIENT_CACHE.put(key, client);
            log.info("创建OSS客户端实例 key => {}", configKey);
            return client;
        } finally {
            LOCK.unlock();
        }
    }
    
    /**
     * 获取本地存储客户端实例
     */
    public static LocalOssClient instanceLocal(String configKey) {
        if (!"local".equals(configKey)) {
            throw new OssException("configKey必须为'local'才能获取本地存储客户端");
        }
        
        String json = CacheUtils.get(CacheNames.SYS_OSS_CONFIG, configKey);
        if (json == null) {
            throw new OssException("系统异常, '" + configKey + "'配置信息不存在!");
        }
        OssProperties properties = JsonUtils.parseObject(json, OssProperties.class);
        // 使用租户标识避免多个租户相同key实例覆盖
        String key = configKey;
        if (StringUtils.isNotBlank(properties.getTenantId())) {
            key = properties.getTenantId() + ":" + configKey;
        }
        
        Object cachedClient = CLIENT_CACHE.get(key);
        LocalOssClient client = null;
        
        // 检查缓存的客户端是否为LocalOssClient类型且配置相同
        if (cachedClient instanceof LocalOssClient) {
            client = (LocalOssClient) cachedClient;
            if (client.checkPropertiesSame(properties)) {
                return client;
            }
        }
        
        // 客户端不存在或配置不相同则重新构建
        LOCK.lock();
        try {
            // 双重检查
            cachedClient = CLIENT_CACHE.get(key);
            if (cachedClient instanceof LocalOssClient) {
                client = (LocalOssClient) cachedClient;
                if (client.checkPropertiesSame(properties)) {
                    return client;
                }
            }
            
            // 创建新的LocalOssClient实例
            client = new LocalOssClient(configKey, properties);
            CLIENT_CACHE.put(key, client);
            log.info("创建本地存储客户端实例 key => {}", configKey);
            return client;
        } finally {
            LOCK.unlock();
        }
    }

}
